
let statusProvider = function (promise, status) {

    return function (data) {
        if (promise.status !== 'pending') {
            return;
        }
        promise.status = status;
        promise.result = data;

        if (status == "resolved") {

            return promise.successListenner.forEach(fn => fn(data));

        } else if (status == "rejected") {
            return promise.failureListenner.forEach(fn => fn(data));
        }

    }
}

class Promise {

    constructor(executor) {
        this.status = "pending";
        this.failureListenner = [];
        this.successListenner = [];
        executor(statusProvider(this, 'resolved'), statusProvider(this, 'rejected'))
    }

    /**
     * 原型方法
     * @param  {...any} args 
     */

    then(...args) {

        setTimeout(() => {

            switch (this.status) {
                case "pending": {
                    this.successListenner.push(args[0]);
                    this.failureListenner.push(args[1]);
                    break;
                }

                case "resolved": {
                    args[0](this.result);
                    break;
                }

                case "rejected": {
                    this.failureListenner.push(args[1])
                }
            }
        }, 0)


    }

    catch(args) {
        return this.then(undefined, args);
    }


}

export default Promise;